package tech.dx.springdb.controller;

import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.dx.springdb.entity.ClassRecords;
import tech.dx.springdb.entity.Student;
import tech.dx.springdb.service.CourseInfoService;
import tech.dx.springdb.service.ParentsService;
import tech.dx.springdb.service.StudentService;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * @ClassName StudentController
 * @Description TODO
 * @Author daoxuan
 * @Date 2019/4/3 14:28
 * @Version 1.0
 */
@RestController
@RequestMapping("student")
@Api(tags = {"学生"})
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private CourseInfoService courseInfoService;
    @Autowired
    private ParentsService parentsService;

    @PostMapping
    public Student add(@RequestBody Student student) {
       /* List<Parents> parents = new LinkedList<>();
        Optional<Parents> byId1 = parentsService.getById(1L);
        Optional<Parents> byId2 = parentsService.getById(4L);
        Parents parents1 = byId1.get();
        Parents parents2 = byId2.get();
        parents.add(parents1);
        parents.add(parents2);
        student.setParentsList(parents);*/
        return studentService.add(student);
    }

    @PutMapping
    public Student update(@RequestBody Student student) {
        return studentService.update(student);
    }

    @GetMapping("/{id}")
    public Student get(@PathVariable long id) {
        return studentService.getById(id);
    }

    @PostMapping(path = ("/{type}/{id}"))
    public void setParentsRelation(@PathVariable long id, @PathVariable String type, @RequestBody String classinfo) {
        Student byId = studentService.getById(id);
        String[] split = classinfo.split(",");
        if ("add".equalsIgnoreCase(type)) {
            LinkedList<ClassRecords> classRecords = new LinkedList<>();
            Arrays.stream(split)
                    .forEach(s -> {
                        ClassRecords classRecords1 = new ClassRecords();
                        BeanUtils.copyProperties(courseInfoService.getById(Long.valueOf(s)), classRecords1);
                        classRecords.add(classRecords1);
                    });
            byId.setClassRecordsList(classRecords);
            studentService.update(byId);
        }
    }

}
